package com.superboo.base.aop;

import com.superboo.core.domain.Result;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * HttpAspect
 *
 * @author peiran zhang
 * @date 2017/3/20
 */
@Aspect
@Component
public class HttpAspect {

    private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);


    //************************************************aop处理log*******************************************************

    /**
     * 定义log切入点
     */
    @Pointcut("execution(public * com.superboo.core.controller.GirlController.*(..))")
    public void initLog() {
    }


    /**
     * 请求之前
     *
     * @param joinPoint
     */
    @Before("initLog()")
    public void logBefore(JoinPoint joinPoint) {

        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attrs.getRequest();

        //url
        logger.info("url={}", request.getRequestURL());

        //method
        logger.info("method={}", request.getMethod());

        //ip
        logger.info("ip={}", request.getRemoteAddr());

        //类方法
        logger.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());

        //参数
        logger.info("args={}", joinPoint.getArgs());
    }

    /**
     * 请求之后
     */
    @After("initLog()")
    public void logAfter() {
        logger.info("22222222");
    }

    /**
     * 得到返回参数
     *
     * @param object
     */
    @AfterReturning(pointcut = "initLog()", returning = "object")
    public void logAfterReturning(Object object) {
        if (object != null && object instanceof Result) {
            logger.info("return={}", object.toString());
        }
    }

    //*********************************************aop处理log结束*******************************************************
}
